package com.paishen.peiniwan.module.profile;

import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.paishen.common.dialog.LoadingDialog;
import com.paishen.common.util.BaseUtil;
import com.paishen.peiniwan.App;
import com.paishen.peiniwan.BaseActivity;
import com.paishen.peiniwan.BusEvent;
import com.paishen.peiniwan.C;
import com.paishen.peiniwan.R;
import com.paishen.peiniwan.frame.PnwOkCallbackAdapter;
import com.paishen.peiniwan.frame.WebActivity;
import com.paishen.peiniwan.frame.http.PnwHttpManager;
import com.paishen.peiniwan.frame.http.entity.Balance;
import com.paishen.peiniwan.frame.http.response.HttpRespData;
import com.squareup.okhttp.Request;

import de.greenrobot.event.EventBus;


/**
 * Created by Administrator on 2015/12/1.
 */
public class MainProfileBalanceLayout extends LinearLayout {

    private long clickTimestamp;
    private final TextView txBalance;
    private final TextView txExtract;

    private Float amount;
    private float result;
    private final LoadingDialog dlgLoading;

    public MainProfileBalanceLayout(Context context) {
        this(context, null);
    }

    public MainProfileBalanceLayout(Context context, AttributeSet attrs) {
        super(context, attrs);
        setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                // interrupt click event
            }
        });
        LayoutInflater.from(context).inflate(R.layout.layout_main_profile_balance, this);
//        ((ViewGroup) getChildAt(0)).getChildAt(0).setPadding(0, (int) getResources().getDimension(R.dimen.title_height) + (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT ? BaseUtil.getStatusBarHeight() : 0), 0, 0);
        setPadding(0, (int) getResources().getDimension(R.dimen.title_height) + (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT ? BaseUtil.getStatusBarHeight() : 0), 0, 0);

        dlgLoading = new LoadingDialog.Builder(getContext()).setCanCancel(false).create();

        txBalance = (TextView) findViewById(R.id.tx_balance);
        txExtract = (TextView) findViewById(R.id.tx_extract);

        initWallet();

        View.OnClickListener l = new OnClickListener() {
            @Override
            public void onClick(View v) {
                final long currClickTimestamp = System.currentTimeMillis();
                if (currClickTimestamp - clickTimestamp < 500) return;
                clickTimestamp = currClickTimestamp;

                switch (v.getId()) {
                    case R.id.tx_extract: {
                        Intent intent = new Intent(v.getContext(), WebActivity.class);
                        intent.putExtra(WebActivity.EXTRA_URL, PnwHttpManager.URL_SERVICE_PAY_EXTRACT);
                        v.getContext().startActivity(intent);
                        break;
                    }
                    case R.id.lay_balance_coupon: {
                        Intent intent = new Intent(v.getContext(), ProfileBalanceCouponActivity.class);
                        v.getContext().startActivity(intent);
                        break;
                    }
                    case R.id.lay_balance_detail: {
                        Intent intent = new Intent(v.getContext(), ProfileBalanceDetailActivity.class);
                        v.getContext().startActivity(intent);
                        break;
                    }
                    case R.id.lay_balance_record: {
                        Intent intent = new Intent(v.getContext(), ProfileBalanceRecordActivity.class);
                        v.getContext().startActivity(intent);
                        break;
                    }
                }
            }
        };

        txExtract.setOnClickListener(l);
        findViewById(R.id.lay_balance_coupon).setOnClickListener(l);
        findViewById(R.id.lay_balance_detail).setOnClickListener(l);
        findViewById(R.id.lay_balance_record).setOnClickListener(l);

        requestWalletGet();
    }

    public void initWallet() {
        com.paishen.peiniwan.database.User user = App.i().getUser();
        amount = user.getAmount();

        result = amount != null ? amount.floatValue() : 0;

        txBalance.setText(String.valueOf((int) result));
        if (result <= 0) {
            txExtract.setEnabled(false);
            txExtract.setTextColor(0xFFB3B3B3);
        } else {
            txExtract.setEnabled(true);
            txExtract.setTextColor(0xFF05131A);
        }
    }

    private void requestWalletGet() {
        final Float m = amount;
        if (m == null) dlgLoading.show(); // first time request

        PnwHttpManager.Wallet.get(((BaseActivity) getContext()).TAG, new PnwOkCallbackAdapter<HttpRespData<Balance>>() {
            @Override
            public void onResponse(HttpRespData<Balance> response, boolean fresh) {
                super.onResponse(response, fresh);
                if (m == null) dlgLoading.dismiss();

                if (response.errcode == C.http.RESULT_SUCCESS) {
                    com.paishen.peiniwan.database.User u = App.i().getUser();
                    u.setAmount(response.data.amount);

                    EventBus.getDefault().post(new BusEvent(BusEvent.TYPE_BACKGROUND, BusEvent.ACTION_DB_UPDATE_USER, u));

                    initWallet();
                } else if (fresh && response.errcode != C.http.RESULT_LOGIN_EXPIRE &&
                        response.errcode != C.http.RESULT_LOGIN_OFFLINE) {
                    BaseUtil.showToast(response.errmsg);
                }
            }

            @Override
            public void onFailure(Request request, Exception e) {
                super.onFailure(request, e);
                initWallet();
            }
        });
    }
}
